# -*- coding:UTF-8 -*-
from PIL import Image, ImageDraw, ImageFont
import random
import io
import string

def verifycode():
    # 实现一个随机生成四位字母的验证码
    # 参数：null
    # 返回值：(buf, value)
    # buf:内存的缓存图，value：验证码的值
    bg_color = (199,104,40)
    width = 120
    height = 50
    flag = 5
    code = string.ascii_lowercase+string.ascii_uppercase+string.ascii_letters
    value = []

    font = ImageFont.truetype(font='DejaVuSans-Bold', size=30)
    image = Image.new('RGB', (width, height), bg_color)
    draw = ImageDraw.Draw(image)

    for data in range(1000):
        draw.point((random.randint(0, width), random.randint(0, height)), (0,0,0))

    for data in range(4):
        v_f = code[random.randint(0, len(code)-1)]
        value.append(v_f)
        draw.text((flag,10), v_f, (0,0,0),  font=font)
        flag += 30
    buf = io.BytesIO()

    image.save(buf, 'png')
    da = ''.join(value)

    return (buf, da)
